import { defineStore, storeToRefs } from "pinia";

import {
  getSongListDetail,
  getPlaylistDetail,
  getSongs,
  getSongUrl,
} from "../utils/api";

import { watch, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";

type D = {
  playlist: P;
};

type P = {
  coverImgUrl: string;
  name: string;
  tags: any[];
  description: string;
};

type PlayUrlData = {
  url: string;
};

const play = localStorage.getItem("playArr");

type A = {
  picUrl: string;
};

type PlayData = {
  id: number | string;
  al: A;
  name: string;
};

export const useSongPlayStore = defineStore({
  id: "songPlay",
  state: () => {
    return {
      //播放、暂停
      tag: -1,
      //播放状态：0：顺序播放，1：循环播放，2：随机播放
      playStatus: 0,
      playData: {} as PlayData,
      playUrlData: {} as PlayUrlData,
      audio: new Audio(),
      //歌单列表
      songList: [] as any[],
      //歌曲总时长
      duration: 0,
      //目前播放的时长
      currentTime: 0,
      //音量
      volume: Number(localStorage.getItem("volume")) || 50,
      //是否播放结束
      ended: false,
      //歌单列表
      playArr: play ? JSON.parse(play) : [],
      onOff: false,
      //歌单详情
      playlistDetail: {} as D,
    };
  },
  getters: {},
  actions: {
    //获取歌单所有歌曲
    async actionSongList(id: string) {
      this.songList = await getSongs(id);
    },
    //获取歌单详情
    async actionPlayListDetail(id: number | string) {
      this.playlistDetail = await getPlaylistDetail(id);
    },
    //设置音量
    initVolume() {
      this.audio.volume = this.volume / 100;
    },
    //点击播放
    async clickPlay(id: number) {
      this.onOff = true;
      if (this.tag === id) {
        return this.audio.play();
      }
      this.tag = id;
      this.getSongUrlData(id);
      this.initVolume();
    },
    async getSongUrlData(id: number) {
      let [obj] = await getSongUrl(id);
      if (!obj.url) {
        ElMessage.error("歌曲获取失败，即将为您播放下一曲");
        return setTimeout(() => {
          this.next();
        }, 500);
      }
      let status = this.playArr.some((item: any) => item.id === id);
      let index = this.songList.findIndex((item) => item.id === id);
      if (!status) {
        this.playArr.push(this.songList[index]);
        localStorage.setItem("playArr", JSON.stringify(this.playArr));
      }
      this.playUrlData = obj;
      this.playData = await getSongListDetail(id);
      this.audio.src = this.playUrlData.url;
      this.audio.play();
    },
    //暂停
    pause() {
      this.onOff = false;
      this.audio.pause();
    },
    //播放
    playMusic() {
      if (!this.tag) return;
      this.onOff = true;
      this.audio.play();
      this.initVolume();
    },
    //上一曲
    last() {
      this.playDetail(true);
    },
    //下一曲
    next() {
      this.playDetail();
    },
    //播放详情
    playDetail(isUp: boolean = false) {
      switch (this.playStatus) {
        case 0:
          let index = this.playArr.findIndex(
            (item: { id: string | number }) => item.id === this.tag
          );
          if (!isUp) {
            let id =
              index === this.playArr.length - 1
                ? this.playArr[0].id
                : this.playArr[index + 1].id;
            this.clickPlay(id);
          } else {
            let id =
              index === 0
                ? this.playArr[this.playArr.length - 1].id
                : this.playArr[index - 1].id;
            this.clickPlay(id);
          }
          break;
        case 1:
          this.playOne();
          break;
        case 2:
          this.shuffleOnce();
          break;
      }
    },
    //播放结束
    playEnd() {
      this.playDetail();
    },
    //随机播放
    shuffleOnce() {
      let randomNum = Math.floor(Math.random() * this.playArr.length);
      this.getSongUrlData(this.playArr[randomNum].id);
      this.tag = this.playArr[randomNum].id;
    },
    //单曲循环
    playOne() {
      this.audio.src = this.playUrlData.url;
      this.audio.play();
    },
    //切换播放状态
    changePlayStatus(val: number) {
      this.playStatus = val;
    },
    //进度条
    onInput(val: number) {
      this.currentTime = val;
      this.audio.currentTime = val;
    },
    //音量条
    volumeInput(val: number) {
      localStorage.setItem("volume", JSON.stringify(val));
      this.initVolume();
    },
    //定时器
    interval() {
      if (this.tag === -1 && !this.ended) return;
      this.currentTime = parseInt(this.audio.currentTime.toString());
      this.duration = parseInt(this.audio.duration.toString());
      this.ended = this.audio.ended;
    },
    //切换数据
    changeData(data: any[]) {
      this.songList = data;
    },
    //删除播放列表的某一项
    removeItem(index: number) {
      this.playArr.splice(index, 1);
      localStorage.setItem("playArr", JSON.stringify(this.playArr));
      if (!this.onOff) {
        this.next();
      }
    },
  },
});

export const userPlayerInit = () => {
  let timer: any;
  const { initVolume, interval, playEnd } = useSongPlayStore();

  const { ended } = storeToRefs(useSongPlayStore());

  //监听播放结束
  watch(ended, (ended) => {
    if (!ended) return;
    playEnd();
  });

  //启动定时器
  onMounted(() => {
    initVolume();
    timer = setInterval(interval, 1000);
  });
  //清除定时器
  onUnmounted(() => {
    clearInterval(timer);
  });
};
